#https://blog.csdn.net/qq_42755230/article/details/144764767
import os
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import START, MessagesState, StateGraph
 
from langchain_community.llms import Tongyi
 
chatLLM = Tongyi()
# 创建一个工作流图


# 定义模型调用函数
def call_model(state: MessagesState):
    response = chatLLM.invoke(state["messages"])
    return {"messages": response}

def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance


class Appc:
    
    def __init__(self, value):
        self.value = value
        workflow = StateGraph(state_schema=MessagesState)

        # 定义图的点和边
        workflow.add_edge(START, "model")  
        workflow.add_node("model", call_model)

        # 添加记忆功能
        memory = MemorySaver()   # 定义了一个内存保存对象，用于在运行过程中保存状态。
        app = workflow.compile(checkpointer=memory)  # 将 MemorySaver 集成到工作流中，使工作流能够在运行中保存和恢复状态。
        self.app=app
    def wf(self):
        return self.app 
 
appc=Appc(1);
def wf():
    workflow = StateGraph(state_schema=MessagesState)

    # 定义图的点和边
    workflow.add_edge(START, "model")  
    workflow.add_node("model", call_model)

    # 添加记忆功能
    memory = MemorySaver()   # 定义了一个内存保存对象，用于在运行过程中保存状态。
    app = workflow.compile(checkpointer=memory)  # 将 MemorySaver 集成到工作流中，使工作流能够在运行中保存和恢复状态。
    return app

def cf(tid):
    config = {"configurable": {"thread_id": tid}}
    return 

def msg(query):
    input_messages = [HumanMessage(query)]
    return input_messages



def ask(query,tid):
    app=appc.wf() 
    config = {"configurable": {"thread_id": tid}}
    input_messages = [HumanMessage(query)]
    output = app.invoke({"messages": input_messages}, config)
    print(output)
    return output

def test():
    ask("桂枝汤","123456")
    ask("副作用","123456")